<?php namespace Summer\Hjd\Classes;

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use RainLab\User\Models\User as UserModel;
use Db;
use Summer\Box\Models\BoxOrderModel;
use Summer\Box\Models\BoxYejiModel;
use Summer\Hjd\Models\BonusRuleModel;
use Summer\Hjd\Models\WalletModel;


class BonusApi
{
    /**
     * 盲盒结算
     */
    public function box_bonus($order){
//        $active_user=UserModel::where('id',$order->buy_uid)->first();
        $active_user=UserModel::where('id',$order->sell_uid)->first();
        $yeji=$order->total_buy;
        //直推奖励+间推奖励
        $this->money_tuijian($active_user,$yeji,$order);
        //爱心购+商品收益
        $this->money_heart($active_user,$yeji,$order);
        //增加业绩
        $this->add_yeji($active_user,$yeji);
        //极差结算-第二日秒结
        $jicha_type=2;
        if($jicha_type==2){
            $bc_jicha=BonusRuleModel::where('group','jicha')->get();
            foreach ($bc_jicha as $bjv){
                $bc_arr[$bjv->rule_level]=$bjv->rule_value;
            }
            $this->money_jicha($active_user,$yeji,$bc_arr);
        }

    }

    /**
     * 增加团队业绩
     */
    public function add_yeji($active_user,$yeji){
        $tids=str2arr($active_user->tids);
        $td_data['yeji_td'] = Db::raw('`yeji_td`+' . $yeji);
        $td_data['yeji_td_total'] = Db::raw('`yeji_td_total`+' . $yeji);
        $td_data['yeji_num'] = Db::raw('`yeji_num`+1');
        $td_data['yeji_num_total'] = Db::raw('`yeji_num_total`+1');
        UserModel::whereIn('id',$tids)->update($td_data);
        //zp修改，考核的伞下的，不包括个人业绩
//        $self_data['yeji_td'] = Db::raw('`yeji_td`+' . $yeji);
//        $self_data['yeji_td_total'] = Db::raw('`yeji_td_total`+' . $yeji);
//        $self_data['yeji_num'] = Db::raw('`yeji_num`+1');
//        $self_data['yeji_num_total'] = Db::raw('`yeji_num_total`+1');
        $self_data['yeji_self'] = Db::raw('`yeji_self`+' . $yeji);
        $self_data['yeji_self_total'] = Db::raw('`yeji_self_total`+' . $yeji);
        UserModel::where('id',$active_user->id)->update($self_data);
        //增加每日业绩累计
        $yeji_today=BoxYejiModel::whereDate('created_at',Carbon::today())->first();
        if($yeji_today){
            $yeji_today->money=$yeji_today->money+$yeji;
            $yeji_today->save();
        }else{
            $yeji_table=new BoxYejiModel();
            $yeji_table->money=$yeji;
            $yeji_table->save();
        }
    }
    /**
     * 爱心购+商品收益
     */
    public function money_heart($active_user,$yeji,$order){
        $bc_heart=BonusRuleModel::where('slug','heart')->first();
        $hj_money=$yeji*$bc_heart->rule_value*0.01;
        //加商品收益
        $line_money=$order->jifen_pay-$order->jifen_buy-$hj_money;
        $table_id=$order->id;
        $table_name='summer_box_orders';

        if($line_money>0){

            $currency_slug_line='line';
            $change_slug_line='bonus_line';
            $commonapi=new CommonApi();
            $commonapi->settleDetailed($active_user->id,$active_user->id,$line_money,1,$currency_slug_line,[
                'change_slug'=>$change_slug_line,
                'table_id'=>$table_id,
                'table_name'=>$table_name,
            ]);

            if($hj_money>0){
                $currency_slug='heart';
                $change_slug='bonus_heart';
                $commonapi=new CommonApi();
                $commonapi->settleDetailed($active_user->id,$active_user->id,$hj_money,1,$currency_slug,[
                    'change_slug'=>$change_slug,
                    'table_id'=>$table_id,
                    'table_name'=>$table_name,
                ]);
            }
        }


    }

    /**
     * 直推加间推奖励
     */
    public function money_tuijian($active_user,$yeji,$order){
        $bc_tuijian=BonusRuleModel::where('slug','tuijian')->first();
        $zt_money=$yeji*$bc_tuijian->rule_value*0.01;
        $jt_money=$yeji*$bc_tuijian->rule_a*0.01;
        $zt_user=UserModel::where('id',$active_user->tuid)->first();
        $table_id=$order->id;
        $table_name='summer_box_orders';
        if($zt_user){
            if($zt_money>0){
                $zt_currency_slug='bonus';
                $zt_change_slug='bonus_zhitui';
                $commonapi=new CommonApi();
                $commonapi->settleDetailed($zt_user->id,$active_user->id,$zt_money,1,$zt_currency_slug,[
                    'change_slug'=>$zt_change_slug,
                    'table_id'=>$table_id,
                    'table_name'=>$table_name,
                ]);
            }
            $jt_user=UserModel::where('id',$zt_user->tuid)->first();
            if($jt_user){
                if($jt_money>0){
                    $jt_currency_slug='score';
                    $jt_change_slug='bonus_jiantui';
                    $commonapi=new CommonApi();
                    $commonapi->settleDetailed($jt_user->id,$active_user->id,$jt_money,1,$jt_currency_slug,[
                        'change_slug'=>$jt_change_slug,
                        'table_id'=>$table_id,
                        'table_name'=>$table_name,
                    ]);
                }
            }
        }
    }

    /**
     * 每日自动或手动升级
     */
    public function uplevel(){
        //考核新级别之前，初始化昨天级别-用隔天结算的方法
        $init_data['levels_code'] = 0;
        UserModel::where('id','>',0)->update($init_data);

        $this->up_l1();
        $this->up_l2();
        $this->up_l3();
        $this->up_l4();
    }
    public function up_l1(){
        $bc_up=BonusRuleModel::where('slug','jicha1')->first();
        $chunk_num = 50;
        UserModel::where('yeji_td','>=',$bc_up->rule_a)->chunk($chunk_num,function ($records){
            foreach ($records as $record){
                //升级
                $record->levels_code=1;
                $record->num_l1=1;
                $record->save();
                //增加团队体验店人数
                $tids=str2arr($record->tids);
                UserModel::whereIn('id',$tids)->increment('num_l1');
            }
        });
    }
    public function up_l2(){
        $bc_up=BonusRuleModel::where('slug','jicha2')->first();
        $chunk_num = 50;
        $need_count=$bc_up->rule_b;
        UserModel::where('yeji_td','>=',$bc_up->rule_a)->chunk($chunk_num,function ($records) use($need_count){
            foreach ($records as $record){
                //判断培养的部门数 ll_count=last_level_count
                $ll_count=UserModel::where('tuid',$record->id)->where('num_l1','>',0)->count();
                if($ll_count>=$need_count){
                    //升级
                    $record->levels_code=2;
                    $record->num_l2=1;
                    $record->save();
                    //增加团队体验店人数
                    $tids=str2arr($record->tids);
                    UserModel::whereIn('id',$tids)->increment('num_l2');
                }

            }
        });
    }
    public function up_l3(){
        $bc_up=BonusRuleModel::where('slug','jicha3')->first();
        $chunk_num = 50;
        $need_count=$bc_up->rule_b;
        UserModel::where('yeji_td','>=',$bc_up->rule_a)->chunk($chunk_num,function ($records) use($need_count){
            foreach ($records as $record){
                //判断培养的部门数 ll_count=last_level_count
                $ll_count=UserModel::where('tuid',$record->id)->where('num_l2','>',0)->count();
                if($ll_count>=$need_count){
                    //升级
                    $record->levels_code=3;
                    $record->num_l3=1;
                    $record->save();
                    //增加团队体验店人数
                    $tids=str2arr($record->tids);
                    UserModel::whereIn('id',$tids)->increment('num_l3');
                }

            }
        });
    }
    public function up_l4(){
        $bc_up=BonusRuleModel::where('slug','jicha4')->first();
        $chunk_num = 50;
        $need_count=$bc_up->rule_b;
        UserModel::where('yeji_td','>=',$bc_up->rule_a)->chunk($chunk_num,function ($records) use($need_count){
            foreach ($records as $record){
                //判断培养的部门数 ll_count=last_level_count
                $ll_count=UserModel::where('tuid',$record->id)->where('num_l3','>',0)->count();
                if($ll_count>=$need_count){
                    //升级
                    $record->levels_code=4;
                    $record->save();
                }
            }
        });
    }

    /**
     * 加权分红-注意比例是千分之几
     */
    public function money_jiaquan(){
        $bc_jiaquan=BonusRuleModel::where('slug','jiaquan')->first();
        if($bc_jiaquan->status!=1){//这里加一个开关
            return false;
        }
        $yeji_today=BoxYejiModel::whereDate('created_at',Carbon::today())->first();
        $yeji=$yeji_today->money??0;
        $qjd_count=UserModel::where('levels_code',4)->count();
        if($qjd_count>0){
            $hj_money=($yeji*$bc_jiaquan->rule_value*0.001)/$qjd_count;
            if($hj_money>0){
                $chunk_num=50;
                UserModel::where('levels_code',4)->chunk($chunk_num,function ($records) use($hj_money){
                    foreach ($records as $record){
                        $currency_slug='stock';
                        $change_slug='bonus_fenhong';
                        $commonapi=new CommonApi();
                        $commonapi->settleDetailed($record->id,$record->id,$hj_money,1,$currency_slug,[
                            'change_slug'=>$change_slug,
                        ]);
                    }
                });
            }
        }
    }

    /**
     * 极差结算-每日系统核算的入口，和秒结的二选一
     */
    public function bonus_jicha(){
        $jicha_type=2;
        if($jicha_type==2){
            return false;
        }
        $bc_jicha=BonusRuleModel::where('group','jicha')->get();
        foreach ($bc_jicha as $bjv){
            $bc_arr[$bjv->rule_level]=$bjv->rule_value;
        }
        $chunk_num=50;
        UserModel::where('yeji_self','>',0)->chunk($chunk_num,function ($records) use($bc_arr){
            foreach ($records as $record){
                $this->money_jicha($record,$record->yeji_self,$bc_arr);
            }
        });
    }

    /**
     * 极差奖励
     * @param $active_user
     * @param $yeji
     */
    public function money_jicha($active_user,$yeji,$bc_arr){
        $tids=str2arr($active_user->tids);
        $user_list=UserModel::whereIn('id',$tids)->where('levels_code','>=',1)->orderBy('id','DESC')->get();
        if(!$user_list->isEmpty()) {
            $last_level = 0;
            $last_ratio = 0;
            foreach ($user_list as $ulv){
                if($ulv->levels_code>$last_level){
                    $last_level=$ulv->levels_code;
                    $hj_money=$yeji*($bc_arr[$ulv->levels_code]-$last_ratio)*0.001;
                    $last_ratio=$bc_arr[$ulv->levels_code];
                    if($hj_money>0){
                        $currency_slug='stock';
                        $change_slug='bonus_jicha';
                        $commonapi=new CommonApi();
                        $commonapi->settleDetailed($ulv->id,$active_user->id,$hj_money,1,$currency_slug,[
                            'change_slug'=>$change_slug,
                        ]);
                    }
                }
                if($last_level>=4){
                    break;
                }
            }
        }
    }

    /**
     * 初始化业绩
     */
    public function inityeji(){
        $init_data['yeji_td'] = 0;
        $init_data['yeji_self'] = 0;//本来用来日发分红的，现在用来考核活跃用户-又启用了，用yeji_self_total考核活跃用户
        $init_data['yeji_num'] = 0;
        $init_data['num_l1'] = 0;
        $init_data['num_l2'] = 0;
        $init_data['num_l3'] = 0;
        UserModel::where('id','>',0)->update($init_data);
    }

    /**
     * 未支付的订单扣积分
     */
    public function ordercheck(){
        $bc_order_check=BonusRuleModel::where('slug','order_check')->first();
        if($bc_order_check->status!=1){//这里有一个开关
            return false;
        }
        $hour=$bc_order_check->rule_a;
        $red_money=$bc_order_check->rule_value;
        //如，一小时前
        $ago_time=Carbon::now()->subHours($hour);
        $chunk_num=50;
        BoxOrderModel::where('status',1)->whereDate('created_at','<',$ago_time)->chunk($chunk_num,function ($records) use($red_money){
            foreach ($records as $record){
                //扣钱
                $this->redcash($record->buy_uid,$red_money,$record->id);
            }
        });

    }

    /**
     * 扣除招商积分
     */
    public function redcash($user_id,$red_money,$order_id){
        $currency_slug='cash';
        //余额判断
        $balance=WalletModel::where('currency_slug',$currency_slug)->where('user_id',$user_id)->value('balance');
        if($red_money>$balance){
            $pay_money=$balance;
        }else{
            $pay_money=$red_money;
        }
        $next_money=$red_money-$balance;
        if($pay_money>0){
            $commonapi=new CommonApi();
            $commonapi->settleDetailed($user_id,$user_id,$pay_money,0,$currency_slug,[
                'change_slug'=>'check_red',
                'table_id'=>$order_id,
                'table_name'=>'summer_box_orders'
            ]);
        }
        if($next_money>0){
            $this->redcash($user_id,$next_money,$order_id);
        }

    }
    public function redbonus($user_id,$red_money,$order_id){
        $currency_slug='bonus';
        //余额判断
        $balance=WalletModel::where('currency_slug',$currency_slug)->where('user_id',$user_id)->value('balance');
        if($red_money>$balance){
            $pay_money=$balance;
        }else{
            $pay_money=$red_money;
        }
        $next_money=$red_money-$balance;
        if($pay_money>0){
            $commonapi=new CommonApi();
            $commonapi->settleDetailed($user_id,$user_id,$pay_money,0,$currency_slug,[
                'change_slug'=>'check_red',
                'table_id'=>$order_id,
                'table_name'=>'summer_box_orders'
            ]);
        }
    }

    /**
     * 批量发放扣除
     */
    public function fafangRed($currency_slug){
        $chunk_num=50;
        WalletModel::where('currency_slug',$currency_slug)->where('balance','>',0)->chunk($chunk_num,function ($records) use($currency_slug){
            foreach ($records as $record){
                $commonapi=new CommonApi();
                $commonapi->settleDetailed($record->user_id,$record->user_id,$record->balance,0,$currency_slug,[
                    'change_slug'=>'fafang_red',
                ]);
            }
        });
    }
}
